odoo.define('ks_list_view_manager.controller', function (require) {
    "use strict";

    var core = require('web.core');
    var fieldUtils = require('web.field_utils');
    var ListController = require('web.ListController');

    var _t = core._t;

    ListController.include({

        custom_events: _.extend({}, ListController.prototype.custom_events,{
            Ks_update_advance_search_renderer : "Ks_update_advance_search_controller",
            ks_remove_domain:"ks_remove_popup_domain",
            ks_update: "ks_update_columns",
        }),

        init: function (parent, model, renderer, params) {
            this.check = parent.className && parent.className.search("o_content") >=0 ? true:false;
            renderer.check = this.check;
            if(this.check) {
                this.ks_list_view_data = params.ks_lvm_data ? params.ks_lvm_data.ks_lvm_user_mode_data : false;
                this._super.apply(this, arguments);
                this.ks_lvm_mode = parent.className && parent.className.search("o_content") >=0 ? true:false;
                renderer.ks_lvm_mode = this.ks_lvm_mode;
                this.ks_lvm_mode = true;
                this.ksViewID = params.ks_lvm_data.ksViewID;
                this.ks_fields_data = params.ks_lvm_data && params.ks_lvm_data.ks_lvm_user_table_result ? params.ks_lvm_data.ks_lvm_user_table_result.ks_fields_data : false;
                if(!this.ks_fields_data) this.ks_fields_data = renderer.ks_fields_data;
                this.ks_lvm_user_mode_data = params.ks_lvm_data ? params.ks_lvm_data.ks_lvm_user_mode_data : false;
                this.ks_autocomplete_data = {};
            }
            else{
                this._super.apply(this, arguments);
            }
        },

        ks_remove_popup_domain: function(ks_options) {
                if(this.check){
                var self = this;
                var ks_i;
                var key;
                var key_array;

                if(ks_options.data.ksDiv!==undefined) {
                    key_array = ks_options.data.ksDiv.id.split("_value")
                    key = key_array[0];
                } else {
                    key = event.target.id;
                }

                if(self.renderer.ks_field_domain_dict[key]!==undefined){
                    if(self.renderer.ks_field_domain_dict[key].length === 1 || ks_options.data.ksfieldtype === "date" || ks_options.data.ksfieldtype === "datetime") {
                         delete self.renderer.ks_field_domain_dict[key];
                         for(ks_i = 0;ks_i < self.renderer.ks_key_fields.length; ks_i++) {
                            if(key === self.renderer.ks_key_fields[ks_i]) {
                                   break;
                            }
                    }

                if(ks_options.data.ksDiv!==undefined) {
                        $("#"+ks_options.data.ksDiv.id).remove()
                } else {
                        $("#"+$(ks_options.data.event.target).parent().children()[$(ks_options.data.event.target).parent().children().length-2].id).remove();
                }

                self.renderer.ks_key_fields.splice(ks_i, 1);
                self.ks_remove_popup_flag = true;
                self.Ks_update_advance_search_controller(false);
                }
                else {
                        for(var j = 0; j < self.renderer.ks_field_domain_dict[key].length; j++) {
                            if(self.renderer.ks_field_domain_dict[key][j] !== '|') {
                                if(ks_options.data.ksDiv!==undefined) {
                                    if(self.renderer.ks_field_domain_dict[key][j][2] === ks_options.data.ksDiv.innerText) {
                                       self.renderer.ks_field_domain_dict[key].splice(j,1)
                                       self.renderer.ks_field_domain_dict[key].splice(0, 1);
                                       break;
                                    }
                                } else {
                                        self.renderer.ks_field_domain_dict[key].splice(j,1)
                                        self.renderer.ks_field_domain_dict[key].splice(0, 1);
                                        break;
                                }
                            }
                        }
                        if(ks_options.data.ksDiv!==undefined) {
                            $("#"+ks_options.data.ksDiv.id).remove()
                        } else {
                            $("#"+$(ks_options.data.event.target).parent().children()[$(ks_options.data.event.target).parent().children().length-2].id).remove();
                        }
                        self.ks_remove_popup_flag=true;
                        self.Ks_update_advance_search_controller(false);
                }
            } else {
                    self.ks_remove_popup_flag=true;
                    self.Ks_update_advance_search_controller(false);
            }
            }
        },

        Ks_update_advance_search_controller: function(ks_options) {
            if(this.check) {
            var self = this;
            if(self.ks_remove_popup_flag === true) {
                var ks_advance_search_params = {};
                ks_advance_search_params["modelName"] = self.renderer.state.model;
                ks_advance_search_params["context"] = self.renderer.state.context;
                ks_advance_search_params["ids"] = self.renderer.state.res_ids;
                ks_advance_search_params["offset"] = self.renderer.state.offset;
                ks_advance_search_params["currentId"] = self.renderer.state.res_id;
                ks_advance_search_params["selectRecords"] = self.renderer.selection
                ks_advance_search_params["groupBy"] = self.renderer.state.groupedBy
                self.renderer.ks_field_domain_list = [];

                for(var j = 0;j < self.renderer.ks_key_fields.length; j++) {
                   self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                }
                self.ks_remove_popup_flag=false;
                ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                if(self.renderer.state.domain.length === 0) {
                    self.renderer.ksBaseDomain = []
                }
                if(self.renderer.ksBaseDomain === null && (self.renderer.ksDomain ===null || self.renderer.ksDomain.length===0) && self.renderer.state.domain.length) {
                    self.renderer.ksBaseDomain = self.renderer.state.domain
                }
                if(self.renderer.ksBaseDomain.length !== 0 || self.renderer.ks_field_domain_list.length !== 0 ) {
                    ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                } else {
                    ks_advance_search_params["domain"] = []
                }
                self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                self.update(ks_advance_search_params,undefined);
            }
            else {
                    var ks_val_flag = false;
                    if(ks_options.data.ks_val){
                       ks_val_flag = ks_options.data.ks_val.trim()!==0
                    } else {
                       ks_val_flag = $('#'+ks_options.data.KsSearchId).val().trim() !== 0
                    }

                    if(Number(ks_val_flag)) {
                    self.ks_advance_search_refresh = true;
                    var ks_search_value = ks_options.data.ks_val || $('#'+ks_options.data.KsSearchId).val().trim();
                    var ks_advance_search_type = ks_options.data.ksfieldtype;
                    var ks_selection_values = [];
                    var ks_advance_search_params ={};
                    self.renderer.ks_field_domain_list=[];
                    self.ks_key_insert_flag = false;
                    var ks_data_insert_flag = false;
                    var ks_value = ks_options.data.KsSearchId.split("_lvm_start_date")
                    ks_advance_search_params["groupBy"] = self.renderer.state.groupedBy
                    ks_advance_search_params["modelName"] = self.renderer.state.model;
                    ks_advance_search_params["context"] = self.renderer.state.context;
                    ks_advance_search_params["ids"] = self.renderer.state.res_ids;
                    ks_advance_search_params["offset"] = self.renderer.state.offset;
                    ks_advance_search_params["currentId"] = self.renderer.state.res_id;
                    ks_advance_search_params["selectRecords"] = self.renderer.selection

                     if(ks_value.length === 1) {
                         ks_value = ks_options.data.KsSearchId.split("_lvm_end_date")
                         if(ks_value.length === 2)
                             ks_options.data.KsSearchId = ks_value[0];
                     }
                     else {
                         ks_options.data.KsSearchId = ks_value[0];
                     }

                     for(var ks_sel_check = 0; ks_sel_check < self.renderer.ks_key_fields.length; ks_sel_check++) {
                         if(ks_options.data.KsSearchId === self.renderer.ks_key_fields[ks_sel_check]) {
                               ks_data_insert_flag = true;
                         }
                     }

                     if((ks_data_insert_flag === false) || (ks_data_insert_flag === true && (ks_advance_search_type === "many2one" || ks_advance_search_type === "many2many"))) {
                           if(!(ks_advance_search_type === "datetime" || ks_advance_search_type === "date")) {
                                if(this.renderer.ks_key_fields.length === 0) {
                                   if(ks_advance_search_type === 'monetary' || ks_advance_search_type === 'integer' || ks_advance_search_type === 'float') {
                                         try{
                                                var currency = self.getSession().get_currency(self.renderer.ks_list_view_data.currency_id);
                                                var formatted_value = fieldUtils.parse.float(ks_search_value || 0, {digits: currency && currency.digits});
                                                ks_search_value  =  formatted_value
                                                self.renderer.ks_key_fields.push(ks_options.data.KsSearchId);
                                            } catch {
                                                    self.do_notify("请输入数字");
                                            }
                                   } else {
                                            self.renderer.ks_key_fields.push(ks_options.data.KsSearchId);
                                   }
                                } else {
                                   for(var key_length = 0; key_length < self.renderer.ks_key_fields.length; key_length++) {
                                         if((self.renderer.ks_key_fields[key_length] === ks_options.data.KsSearchId)) {
                                              self.ks_key_insert_flag = true;
                                              break;
                                         }
                                    }
                                   if(!(self.ks_key_insert_flag)) {
                                         if(ks_advance_search_type === 'monetary' || ks_advance_search_type === 'integer' || ks_advance_search_type === 'float') {
                                                 try{
                                                        var currency = self.getSession().get_currency(self.renderer.ks_list_view_data.currency_id);
                                                        var formatted_value = fieldUtils.parse.float(ks_search_value || 0, {digits: currency && currency.digits});
                                                        ks_search_value  =  formatted_value
                                                        self.renderer.ks_key_fields.push(ks_options.data.KsSearchId);
                                                    } catch {
                                                            self.do_notify("请输入数字");
                                                    }
                                         } else {
                                            self.renderer.ks_key_fields.push(ks_options.data.KsSearchId);
                                         }
                                   }
                               }
                           }

                     if(ks_advance_search_type === "datetime" || ks_advance_search_type === "date") {
                          if(ks_options.data.ksFieldIdentity === ks_options.data.KsSearchId + '_lvm_start_date lvm_start_date') {
                               self.ks_start_date = ks_search_value;
                               self.ks_start_date_id = ks_options.data.KsSearchId;
                          }else {
                                var ks_end_date = new Date(ks_search_value);
                                ks_end_date.setHours(23);
                                ks_end_date.setMinutes(59);
                                ks_end_date.setSeconds(59);
                                self.ks_end_date = ks_end_date.toISOString();
                                self.ks_end_date_id=ks_options.data.KsSearchId
                          }

                          if(ks_advance_search_type==="datetime" || ks_advance_search_type==="date") {
                               if(ks_options.data.ksFieldIdentity === ks_options.data.KsSearchId+'_lvm_end_date lvm_end_date') {
                                    if(self.ks_start_date_id === self.ks_end_date_id) {
                                        self.renderer.ks_field_domain_dict[self.ks_start_date_id] = [[self.ks_start_date_id,'>=', self.ks_start_date], [self.ks_end_date_id,'<=', self.ks_end_date]]
                                        if(self.renderer.ks_key_fields.length === 0) {
                                            self.renderer.ks_key_fields.push(self.ks_start_date_id);
                                        }
                                        else {
                                             for(var key_length = 0;key_length < self.renderer.ks_key_fields.length; key_length++) {
                                                if(!(self.renderer.ks_key_fields[key_length] === ks_options.data.KsSearchId)) {
                                                    self.renderer.ks_key_fields.push(self.ks_start_date_id);
                                                    break;
                                                }
                                             }
                                        }
                                    }
                               }
                          }
                     } else if(ks_advance_search_type === 'selection') {
                          if(ks_search_value === "Select a Selection") {
                                 for(var j=0;j<self.renderer.ks_key_fields.length;j++) {
                                      self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                                 }
                                ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                                if(self.renderer.state.domain.length === 0) {
                                    self.renderer.ksBaseDomain = []
                                }
                                ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                                self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                                self.update(ks_advance_search_params,undefined);
                          } else {

                                // obtaining values of selection
                                ks_selection_values = self.renderer.state.fields[ks_options.data.KsSearchId].selection;

                                //setting values for selection
                                for(var i = 0; i < ks_selection_values.length; i++) {
                                    if(ks_selection_values[i][1] === ks_search_value) {
                                        ks_search_value = ks_selection_values[i][0];
                                    }
                                }
                                self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId] = [[ks_options.data.KsSearchId,'=', ks_search_value]]
                          }
                     } else if (ks_advance_search_type === "many2one" || ks_advance_search_type === "many2many") {
                            if(self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId] === undefined)
                                 self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId] = [[ks_options.data.KsSearchId, "ilike", ks_search_value]]
                            else
                                 self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId].push([ks_options.data.KsSearchId, "ilike", ks_search_value])

                            if(self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId].length>1) {
                                self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId].unshift("|")
                            }
                            ks_advance_search_params["ids"] = self.initialState.res_id;
                     } else if(ks_advance_search_type === 'monetary' || ks_advance_search_type === 'integer' || ks_advance_search_type === 'float') {
                                        self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId] = [[ks_options.data.KsSearchId,'=', ks_search_value]]

                     } else {
                            self.renderer.ks_field_domain_dict[ks_options.data.KsSearchId] = [[ks_options.data.KsSearchId, "ilike", ks_search_value]]
                     }

                    if(ks_advance_search_type === "datetime" || ks_advance_search_type === "date") {
                        if(ks_options.data.ksFieldIdentity === ks_options.data.KsSearchId+'_lvm_end_date lvm_end_date') {
                             for(var j=0; j < self.renderer.ks_key_fields.length; j++) {
                               this.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                        }
                        ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                        if(self.renderer.state.domain.length === 0) {
                            self.renderer.ksBaseDomain = []
                        }
                        ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                        self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                        self.update(ks_advance_search_params,undefined);
                        self.ks_start_date = undefined;
                        self.ks_end_date = undefined;
                        self.ks_start_date_id = undefined;
                        self.ks_end_date_id = undefined;
                    }
                }
                else {
                       if(ks_advance_search_type === 'monetary' || ks_advance_search_type === 'integer' || ks_advance_search_type === 'float') {
                            if(!(isNaN(ks_search_value))) {
                               for(var j = 0; j < self.renderer.ks_key_fields.length; j++) {
                                  self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                               }
                            ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                            if(self.renderer.state.domain.length === 0) {
                                  self.renderer.ksBaseDomain = []
                            }
                            ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                            self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                            self.update(ks_advance_search_params,undefined);
                            }
                            else{
                                    if(self.renderer.state.domain.length === 0) {
                                        self.renderer.ksBaseDomain = []
                                    }
                                    ks_advance_search_params["domain"] = self.renderer.ksDomain || []
                                    self.update(ks_advance_search_params,undefined);
                            }
                       } else {
                            for(var j = 0; j < self.renderer.ks_key_fields.length; j++) {
                                  self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                               }
                            ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                            if(self.renderer.state.domain.length === 0) {
                                self.renderer.ksBaseDomain = []
                            }
                            ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                            self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                            self.update(ks_advance_search_params,undefined);
                       }
                }
            } else {
                      for(var j=0;j<self.renderer.ks_key_fields.length;j++) {
                         self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                      }
                      ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                      if(self.renderer.state.domain.length === 0) {
                            self.renderer.ksBaseDomain = []
                      }
                      ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                      self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                      self.update(ks_advance_search_params,undefined);
                   }
            }
                    else {
                        self.ks_advance_search_refresh = true;
                        var ks_search_value = $('#'+ks_options.data.KsSearchId).val().trim();
                        var ks_advance_search_type = ks_options.data.ksfieldtype;
                        var ks_selection_values = [];
                        var ks_advance_search_params ={};
                        self.renderer.ks_field_domain_list=[];
                        self.ks_key_insert_flag = false;
                        var ks_data_insert_flag = false;
                        var ks_value = ks_options.data.KsSearchId.split("_lvm_start_date")

                        ks_advance_search_params["modelName"] = self.renderer.state.model;
                        ks_advance_search_params["context"] = self.renderer.state.context;
                        ks_advance_search_params["ids"] = self.renderer.state.res_ids;
                        ks_advance_search_params["offset"] = self.renderer.state.offset;
                        ks_advance_search_params["currentId"] = self.renderer.state.res_id;
                        ks_advance_search_params["selectRecords"] = self.renderer.selection
                        ks_advance_search_params["groupBy"] = []

                        for(var j=0;j<self.renderer.ks_key_fields.length;j++) {
                          self.renderer.ks_field_domain_list = self.renderer.ks_field_domain_list.concat(self.renderer.ks_field_domain_dict[self.renderer.ks_key_fields[j]]);
                        }
                        ks_advance_search_params["ksDomain"] = self.renderer.ks_field_domain_list;
                        if(self.renderer.state.domain.length === 0) {
                            self.renderer.ksBaseDomain = []
                        }
                        ks_advance_search_params["domain"] = self.renderer.ksBaseDomain.concat(self.renderer.ks_field_domain_list)
                        self.renderer.ksDomain = ks_advance_search_params["ksDomain"]
                        self.update(ks_advance_search_params,undefined);
                   }
                }
                }
        },

        update: function (params, options) {
            var self = this;

            if(this.renderer.ks_lvm_data["default_fields"] && arguments[0]["context"]) arguments[0]["context"]["default_fields"] = this.renderer.ks_lvm_data["default_fields"];
            var res = this._super.apply(this,arguments);
            return res.done(function() {
                if(self.ks_lvm_mode){
                        if($(".ks_lvm_o_content").length && (($(".ks_lvm_o_content").offset().top+1) != $(".tableFloatingHeaderOriginal").css("top"))) {
                        $(".tableFloatingHeaderOriginal").css("top",$(".ks_lvm_o_content").offset().top+0.50);
                    }
                }
            });
        },

    });

});


